<template>
  <!--添加分享卡位 -->
  <el-dialog title="新增分享" :visible.sync="dialogVisible" :close-on-click-modal="false" width="650px" append-to-body>
    <div class="form-box">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px" class="demo-ruleForm">
        <el-button type="primary" @click="openSelectKawei">选择卡位</el-button>
        <el-table max-height="300px" :data="telList" border style="width: 100%;margin-top: 10px;" stripe>
          <el-table-column prop="chuzufangName" label="管理方">
            <template slot-scope="scope">
              <span>{{ scope.row.chuzufangName||scope.row.custodian }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="tel" label="手机号" width="130"></el-table-column>
          <el-table-column prop="gameStr" label="游戏运营商">
            <template slot-scope="scope">
              <div class="bangding-box" v-if="scope.row.carrierType">
                <template v-if="carrierTypes&&carrierTypes[1]">
                  <span :key="scope.row.id">
                    {{carrierTypes[scope.row.carrierType].name}}
                  </span>
                </template>
              </div>
              <div v-else>全部</div>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="设备状态" width="100">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.deviceStatus==1" type="success">在线</el-tag>
              <el-tag v-if="scope.row.deviceStatus==2" type="danger">离线</el-tag>
            </template>
          </el-table-column>
        </el-table>
        <!-- <el-form-item label="运营商" prop="gameCarrierIdsArr">
          <el-select multiple v-model="form.gameCarrierIdsArr" placeholder="请选择游戏游戏运营商" @change="carrierChange">
            <el-option v-for="dict in yunyingshangList" :key="dict.id" :label="dict.name" :value="dict.id" />
          </el-select>
        </el-form-item> -->
        <div style="height: 10px;"></div>
        <el-form-item label="游戏账号" prop="pwd">
          <el-input v-model="form.pwd" placeholder="请输入游戏账号" />
        </el-form-item>
        <el-form-item label="短信显示数量" prop="num">
          <el-input v-model="form.num" placeholder="请输入短信显示数量" />
        </el-form-item>
        <el-form-item label="到期时间" prop="expireTime">
          <el-date-picker style="width:250px" v-model="form.expireTime" type="datetime" placeholder="请选择到期时间" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="短信过滤" prop="guolv">
          <el-input v-model="form.guolv" type="textarea" placeholder="请输入关键字，包含关键字的短信将会被过滤掉" :rows="2" style="width:400px" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请填写备注" :rows="4" style="width:400px" />
        </el-form-item>

        <div class="tip">
          提示：分享链接后，任何人打开链接都能看到该手机号接收的短信，请注意账号安全！
        </div>

        <div class="center">
          <el-button @click="close()">取消</el-button>
          <el-button type="primary" @click="submitForm('form')" v-loading="loading">提交</el-button>
        </div>
      </el-form>
    </div>
    <selectKawei ref="selectKawei" @change="kaweiSelected"></selectKawei>
  </el-dialog>
</template>

<script>
import phoneApi from "@/api/phoneManage";
import selectKawei from "./selectKawei.vue";
export default {
  name: "",
  components: { selectKawei },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value && value.length != 11) {
        callback(new Error("请输入11位手机号"));
      } else {
        callback();
      }
    };
    return {
      dialogVisible: false,
      loading: false,
      yunyingshangList: [],

      // 表单参数
      form: {
        pwd: "",
        num: "",
        expireTime: "",
        tenantId: "",
        tenantName: "",
        remark: "",
      },
      Code_url: "",
      rules: {
        num: [{ required: true, message: "请输入短信数量", trigger: "blur" }],
        expireTime: [
          { required: true, message: "请输入到期时间", trigger: "change" },
        ],
      },
      telList: [],
      telInfos: [],
      zulinType: 2,
    };
  },
  created() {},
  computed: {
    shopInfo() {
      return this.$store.getters.shopInfo;
    },
    retailDomain() {
      return this.$store.getters.retailDomain;
    },
    carrierTypes() {
      return this.arrayToObject(this.$store.getters.gameYunyingshangList, "id");
    },
  },
  methods: {
    // 打开弹窗
    open(data, flag) {
      if (!this.shopInfo) {
        return this.$message.error("非店铺账户不能改分享！");
      }
      this.yunyingshangList = this.$store.getters.gameYunyingshangList;
      this.telList = [];
      this.telInfos = [];
      if (flag == "edit") {
        // 编辑
        this.form = { ...data };
        this.form.gameCarrierIdsArr = [];
        if (data.gameCarrierIds) {
          const arr = data.gameCarrierIds.split(",");
          if (arr && arr.length) {
            arr.forEach((r) => {
              this.form.gameCarrierIdsArr.push(Number(r));
            });
          }
        }
      } else {
        // 新增
        if (flag == "wozude") {
          this.zulinType = 2;
        } else {
          this.zulinType = 1;
        }
        if (flag == "wozude" && data && data.length) {
          this.telList = JSON.parse(JSON.stringify(data));

          this.setTelInfos();
        }
        this.form.tenantId = this.shopInfo.tenantId;
        this.form.tenantName = this.shopInfo.tenantName;
      }

      this.dialogVisible = true;
    },
    // 处理选中的条目
    setTelInfos() {
      this.telInfos = [];
      if (this.telList && this.telList.length) {
        if (this.zulinType == 2) {
          // 我租的
          const newTellist = this.mergeDuplicateByTelId(this.telList)
          // console.log("%c Line:169 🍎 newTellist", "color:#7f2b82", newTellist);
          newTellist.forEach((r) => {
            // let gameCarrierIds = [];
            // let gameCarrierNames = [];
            // if (r.carrierTypeVoList && r.carrierTypeVoList.length) {
            //   r.carrierTypeVoList.forEach((c) => {
            //     gameCarrierIds.push(c.id);
            //     gameCarrierNames.push(c.name);
            //   });
            // }
            this.telInfos.push({
              tel: r.tel,
              gameCarrierIds: r.gameCarrierIds,
              gameCarrierNames: r.gameCarrierNames,
            });
          });
        } else {
          // 我的卡位  直接选中所有运营商
          let gameCarrierIds = [];
          let gameCarrierNames = [];
          this.yunyingshangList.forEach((c) => {
            gameCarrierIds.push(c.id);
            gameCarrierNames.push(c.name);
          });
          this.telList.forEach((r) => {
            r.carrierTypeVoList = this.yunyingshangList;
            this.telInfos.push({
              tel: r.tel,
              gameCarrierIds: gameCarrierIds.join(","),
              gameCarrierNames: gameCarrierNames.join(","),
            });
          });
        }
      }
      this.form.telInfos = JSON.stringify(this.telInfos);
    },
    // 按照teiId合并 整理运营商
    mergeDuplicateByTelId(array) {
      let _this = this
      const result = array.reduce((acc, current) => {
        // console.log("%c Line:210 🍖 current", "color:#ed9ec7", current);
        const existingItem = acc.find((item) => item.telManageId === current.telManageId);
        if (existingItem) {
          // 重复项
          // console.log("%c Line:212 🍰 existingItem", "color:#ed9ec7", existingItem);
          // 合并逻辑 - 这里可以根据需求自定义
          // 例如：合并数组字段或选择保留特定值
          if(existingItem.carrierType){
            const carrierName = _this.carrierTypes[existingItem.carrierType].name
            let carrierName2 = ''
            if(current.carrierType){
              carrierName2 = _this.carrierTypes[current.carrierType].name
            }
            if(existingItem['gameCarrierIds']&&current.carrierType){
              existingItem['gameCarrierIds'] = existingItem['gameCarrierIds']+',' + current.carrierType
              existingItem['gameCarrierNames'] = existingItem['gameCarrierNames']+',' + carrierName2
            }else{
              if(current.carrierType){
                existingItem['gameCarrierIds'] = ''+existingItem.carrierType+','+ current.carrierType
                existingItem['gameCarrierNames'] = ''+carrierName+','+ carrierName2
              }
              
            }
          }
        } else {
          current.gameCarrierIds=''+current.carrierType
          current.gameCarrierNames=''+_this.carrierTypes[current.carrierType].name
          acc.push(current);
        }

        return acc;
      }, []);

      return result;
    },
    // 卡位选择结束
    kaweiSelected(rows) {
      this.telList = JSON.parse(JSON.stringify(rows));
      this.setTelInfos();
    },
    // 选择卡位
    openSelectKawei() {
      this.$refs.selectKawei.open(this.zulinType, this.telList);
    },
    // 重置
    reset() {
      this.$refs.form.resetFields();
    },
    // 选择运营商
    carrierChange(e) {
      // console.log("%c Line:136 🍅 e", "color:#465975", e);
      let gameCarrierNames = [];
      let gameCarrierIds = [];
      if (e && e.length) {
        e.forEach((r) => {
          this.yunyingshangList.forEach((r2) => {
            if (r2.id == r) {
              // console.log("%c Line:143 🥒 r2", "color:#33a5ff", r2);
              gameCarrierNames.push(r2.name);
              gameCarrierIds.push(r2.id);
            }
          });
        });
      }
      this.form.gameCarrierNames = gameCarrierNames.join(",");
      this.form.gameCarrierIds = gameCarrierIds.join(",");
    },
    async submitForm(formName) {
      if (!this.telInfos || this.telInfos.length == 0) {
        return this.$message.error("请先选择卡位！");
      }
      this.$refs["" + formName].validate(async (valid) => {
        if (valid) {
          let res = "";
          if (this.form.id) {
            // 编辑
            res = await phoneApi.appMessageShareEdit(this.form);
            this.$parent.getList();
          } else {
            // 新增

            res = await phoneApi.appMessageShare(this.form);

            let host = "";
            if (this.shopInfo.otherDomain) {
              if (
                this.shopInfo.otherDomain &&
                this.shopInfo.otherDomain.includes(",")
              ) {
                host = this.shopInfo.otherDomain.split(",")[0] + "/";
              } else {
                host = this.shopInfo.otherDomain + "/";
              }
            } else {
              host = this.retailDomain["h5"].dictValue;
            }
            const Code_url = `${host}pages/SMSList/SMSList/?flag=${res.data.randomStr}`;

            this.$confirm(
              `创建分享成功，链接为:${Code_url}, 在“短信记录>我的分享”菜单可查看`,
              "提示",
              {
                confirmButtonText: "复制链接",
                cancelButtonText: "取消",
                type: "warning",
              }
            )
              .then(() => {
                this.$copyText(Code_url).then(() => {
                  this.$message.success("链接已复制到剪切板");
                });
              })
              .catch(() => {});
          }
          this.$message.success(res.msg);
          this.reset();
          this.dialogVisible = false;
        } else {
          this.$alert("请填写完整！");
        }
      });
    },

    close() {
      this.reset();
      this.dialogVisible = false;
    },
  },
};
</script>
<style scoped lang="css">
.center {
  text-align: center;
}

.tip {
  color: red;
  margin-bottom: 20px;
}
::v-deep .el-table--medium .el-table__cell {
  padding: 0;
}
</style>
